package com.web.portal.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.web.portal.entity.Faculty;
import com.web.portal.exception.PortalException;
import com.web.portal.pojo.FacultyPojo;
import com.web.portal.service.FacultyService;
import com.web.portal.validator.AddFacultyValidor;

@Controller
public class AdminManagerController {
	private static final Logger LOG = Logger
			.getLogger(AdminManagerController.class);
	@Autowired
	FacultyService service;
	@Autowired
	AddFacultyValidor addFacultyValidator;

	public FacultyService getService() {
		return service;
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {

		binder.setValidator(addFacultyValidator);
	}

	public void setService(FacultyService service) {
		this.service = service;
	}

	@RequestMapping(value = "/admin/manager.do")
	public String facultyLists(
			Map<String, Object> map,
			@RequestParam(value = "student", required = false) boolean isStudent,
			HttpServletRequest request) throws PortalException {

		Faculty faculty = new Faculty();
		List<Faculty> facultyList = service.getList(faculty);

		/*
		 * sort base don first name, if equal first name than last name
		 */
		Collections.sort(facultyList);
		map.put("facultyList", facultyList);
		

			return "faculty_and_staff";
		

	}

	/*
	 * Display image of the faculty
	 */
	@RequestMapping(value = "/welcome/fetchimage.do", method = RequestMethod.GET)
	public void getImage(@RequestParam("email") final String mail,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, PortalException {
		if (!(mail == null)) {
			Faculty faculty = service.getFacultyImageOrMapFile(mail);
			// byte[] imageBytes = null;

			if (!(faculty.getImage() == null)) {
				response.setContentType("image/jpeg");
				response.setContentLength(faculty.getImage().length);
				try {
					ServletOutputStream out = response.getOutputStream();
					out.write(faculty.getImage());
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		} else {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			LOG.debug("Request parameter provided is null................");
			return;
		}
	}

	@RequestMapping(value = "/welcome/fetchmap.do", method = RequestMethod.GET)
	public void getMap(@RequestParam("email") final String email,
			final String mail, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException, PortalException {
		if (!(email == null)) {
			Faculty faculty = service.getFacultyImageOrMapFile(email);
			// byte[] imageBytes = null;

			if (!(faculty.getMap() == null)) {
				response.setContentType("image/jpeg");
				response.setContentLength(faculty.getMap().length);
				try {
					ServletOutputStream out = response.getOutputStream();
					out.write(faculty.getMap());
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		} else {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			LOG.debug("Request parameter provided is null................");
			return;
		}
	}

	@RequestMapping(value = "/admin/fillInformation.do", method = RequestMethod.GET)
	public String fillFaculty(Model model) throws PortalException {
		model.addAttribute(new FacultyPojo());
		return "add_faculty_info";
	}

	@RequestMapping(value = "/welcome/addFaculty.do", method = RequestMethod.POST)
	public @ResponseBody
	String addFaculty(
			@RequestParam(value = "firstName", required = false) String firstName,
			@RequestParam(value = "lastName", required = false) String lastName,
			@RequestParam(value = "description", required = false) String description,
			@RequestParam(value = "mail", required = false) String email,
			@RequestParam("phone") String phone,
			@RequestParam(value = "research", required = false) String research,
			@RequestParam(value = "myFileImage", required = false) MultipartFile myFileImage,
			@RequestParam(value = "myFileMap", required = false) MultipartFile myFileMap)
			throws IOException {

		Faculty faculty = new Faculty();
		faculty.setFirstName(firstName);
		faculty.setLastName(lastName);
		byte[] image = myFileImage.getBytes();
		faculty.setImage(image);
		byte[] map = myFileMap.getBytes();
		faculty.setMap(map);
		faculty.setDescription(description);
		faculty.setEmail(email);
		faculty.setResearch(research);
		faculty.setPhone(phone);

		if (firstName == null && lastName == null && email == null
				&& phone == null) {
			LOG.debug("please provide first name, last name , email and phone");
			return "redirect:/fillInformation.do";
		} else {
			service.addFaculty(faculty);
			return "redirect:/admin/manager.do";
		}

	}

	@RequestMapping(value = "/admin/addFaculties.do", method = RequestMethod.POST)
	public String addFaculty(
			@ModelAttribute(value = "facultyPojo") @Valid FacultyPojo facultyPojo,
			BindingResult result, Model model) throws IOException, PortalException {

		if (result.hasErrors()) {
			/*
			 * clearing the inputs makes user bored about filling inputs again
			 */
			/*
			 * facultyPojo.setFirstName(""); facultyPojo.setLastName("");
			 * facultyPojo.setDescription(""); facultyPojo.setMyFileImage(null);
			 * facultyPojo.setMyFileMap(null); facultyPojo.setPhone("");
			 * facultyPojo.setResearch("");
			 */
			model.addAttribute(facultyPojo);
			return "add_faculty_info";
		}
		Faculty faculty = new Faculty();
		faculty.setFirstName(facultyPojo.getFirstName());
		faculty.setLastName(facultyPojo.getLastName());
		faculty.setImage(facultyPojo.getMyFileImage().getBytes());
		byte[] map = facultyPojo.getMyFileMap().getBytes();
		faculty.setMap(map);
		faculty.setDescription(facultyPojo.getDescription());
		faculty.setEmail(facultyPojo.getMail());
		faculty.setResearch(facultyPojo.getResearch());
		faculty.setPhone(facultyPojo.getPhone());
		faculty.setPosition(facultyPojo.getPosition());

		service.addFaculty(faculty);
		return "redirect:/admin/manager.do";

	}

}
